//
//  CalendarMonthView.m
//  BBT
//
//  Created by JoyWang on 14-7-11.
//  Copyright (c) 2014年 tiewang. All rights reserved.
//

#import "CalendarMonthView.h"
#import "NSDate+TKCategory.h"
#import "CalendarMonthTiles.h"
#import "NSDate+CalendarGrid.h"
#import "TKGlobal.h"
@interface CalendarMonthView ()
{
}
@property (nonatomic,strong) CalendarMonthTiles *currentTile;
@property (nonatomic,strong) CalendarMonthTiles *oldTile;
@property (nonatomic,strong) UIButton *leftArrow;
@property (nonatomic,strong) UIButton *rightArrow;
@property (nonatomic,strong)UILabel *monthLabel;
@property (nonatomic,strong)UILabel *yearLabel;
@property (nonatomic,strong)UIView *shadowView;
@end
@implementation CalendarMonthView

- (instancetype) initWithSundayAsFirst:(BOOL)sunday timeZone:(NSTimeZone*)timeZone;{
    self = [super initWithFrame:CGRectMake(0, 0,VIEW_WIDTH, VIEW_HEIGHT)];
    if (!self) {
        return nil;
    }
    
    self.sunday = sunday;
    self.timeZone = timeZone;
    
    [self addSubview:self.shadowView];
    [self.shadowView addSubview:self.leftArrow];
    [self.shadowView addSubview:self.rightArrow];
    [self.shadowView addSubview:self.monthLabel];
    [self.shadowView addSubview:self.yearLabel];
    
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
	dateFormat.dateFormat = @"eee";
	dateFormat.timeZone = self.timeZone;
	
	NSDateComponents *sund = [[NSDateComponents alloc] init];
	sund.day = 13;
	sund.month = 7;
	sund.year = 2014;
	sund.hour = sund.minute = sund.second = sund.weekday = 0;
	sund.timeZone = self.timeZone;
    
    NSString * sun = [dateFormat stringFromDate:[NSDate dateWithDateComponents:sund]];
    
	sund.day = 14;
	NSString *mon = [dateFormat stringFromDate:[NSDate dateWithDateComponents:sund]];
	
	sund.day = 15;
	NSString *tue = [dateFormat stringFromDate:[NSDate dateWithDateComponents:sund]];
	
	sund.day = 16;
	NSString *wed = [dateFormat stringFromDate:[NSDate dateWithDateComponents:sund]];
	
	sund.day = 17;
	NSString *thu = [dateFormat stringFromDate:[NSDate dateWithDateComponents:sund]];
	
	sund.day = 18;
	NSString *fri = [dateFormat stringFromDate:[NSDate dateWithDateComponents:sund]];
	
	sund.day = 19;
	NSString *sat = [dateFormat stringFromDate:[NSDate dateWithDateComponents:sund]];
    NSArray *ar;
	if(self.sunday) ar = @[sun,mon,tue,wed,thu,fri,sat];
	else ar = @[mon,tue,wed,thu,fri,sat,sun];
    NSInteger i = 0;
    CGFloat labelWidth = VIEW_WIDTH/7;
	for(NSString *s in ar){
		UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(labelWidth*i + (i==0?0:-1), 30+20, labelWidth, 15)];
		[self.shadowView addSubview:label];
        
        // Added Accessibility Labels
        if ([s isEqualToString:@"Sun"]) {
            label.accessibilityLabel = @"Sunday";
            label.text = @"日";
        } else if ([s isEqualToString:@"Mon"]) {
            label.accessibilityLabel = @"Monday";
            label.text = @"一";
        } else if ([s isEqualToString:@"Tue"]) {
            label.accessibilityLabel = @"Tuesday";
            label.text = @"二";
        } else if ([s isEqualToString:@"Wed"]) {
            label.accessibilityLabel = @"Wednesday";
            label.text = @"三";
        } else if ([s isEqualToString:@"Thu"]) {
            label.accessibilityLabel = @"Thursday";
            label.text = @"四";
        } else if ([s isEqualToString:@"Fri"]) {
            label.accessibilityLabel = @"Friday";
            label.text = @"五";
        } else if ([s isEqualToString:@"Sat"]) {
            label.accessibilityLabel = @"Saturday";
            label.text = @"六";
        }
        
		label.textAlignment = NSTextAlignmentCenter;
		label.font = [UIFont boldSystemFontOfSize:13];
		label.backgroundColor = [UIColor whiteColor];
		label.textColor = [UIColor blackColor];
		i++;
	}
   [self _setupCurrentTileView:[NSDate date]];
    return self;
}

#pragma mark Button Action
- (void) changeMonth:(UIButton *)sender{
	
	NSDate *newDate = [self _dateForMonthChange:sender];
	if ([self.delegate respondsToSelector:@selector(calendarMonthView:monthShouldChange:animated:)] && ![self.delegate calendarMonthView:self monthShouldChange:newDate animated:YES] )
		return;

	
	if ([self.delegate respondsToSelector:@selector(calendarMonthView:monthWillChange:animated:)] )
		[self.delegate calendarMonthView:self monthWillChange:newDate animated:YES];
	
	
	[self changeMonthAnimation:sender];
	if([self.delegate respondsToSelector:@selector(calendarMonthView:monthDidChange:animated:)])
		[self.delegate calendarMonthView:self monthDidChange:self.currentTile.monthDate animated:YES];
	
}


- (NSDate*) _dateForMonthChange:(UIView*)sender {
	BOOL isNext = (sender.tag == 1);
	NSDate *nextMonth = isNext ? [self.currentTile.monthDate nextMonthWithTimeZone:self.timeZone] : [self.currentTile.monthDate previousMonthWithTimeZone:self.timeZone];
	
	NSDateComponents *nextInfo = [nextMonth dateComponentsWithTimeZone:self.timeZone];
	NSDate *localNextMonth = [NSDate dateWithDateComponents:nextInfo];
	
	return localNextMonth;
}
#pragma mark Moving the tiles up and down

- (void) _tileSelectedWithData:(NSArray*)ar{
	
	if(ar.count < 2){
		
		if([self.delegate respondsToSelector:@selector(calendarMonthView:didSelectDate:)])
			[self.delegate calendarMonthView:self didSelectDate:[self dateSelected]];
		
	}else{
		
		NSInteger direction = [[ar lastObject] intValue];
		UIButton *b = direction > 1 ? self.rightArrow : self.leftArrow;
		
		NSDate* newMonth = [self _dateForMonthChange:b];
		if ([self.delegate respondsToSelector:@selector(calendarMonthView:monthShouldChange:animated:)] && ![self.delegate calendarMonthView:self monthShouldChange:newMonth animated:YES])
			return;
		
		if ([self.delegate respondsToSelector:@selector(calendarMonthView:monthWillChange:animated:)])
			[self.delegate calendarMonthView:self monthWillChange:newMonth animated:YES];
		
		[self changeMonthAnimation:b];
		NSInteger day = [ar[0] intValue];
		
		NSDateComponents *info = [[self.currentTile monthDate] dateComponentsWithTimeZone:self.timeZone];
		info.day = day;
        
        NSDate *dateForMonth = [NSDate dateWithDateComponents:info];
		
		if([self.delegate respondsToSelector:@selector(calendarMonthView:didSelectDate:)])
			[self.delegate calendarMonthView:self didSelectDate:dateForMonth];
		
		if([self.delegate respondsToSelector:@selector(calendarMonthView:monthDidChange:animated:)])
			[self.delegate calendarMonthView:self monthDidChange:dateForMonth animated:YES];
		
		[self.currentTile selectDay:day];
		
		
	}
	
}

- (void) changeMonthAnimation:(UIView*)sender{
	
	BOOL isNext = (sender.tag == 1);
	NSDate *nextMonth = isNext ? [self.currentTile.monthDate nextMonthWithTimeZone:self.timeZone] : [self.currentTile.monthDate previousMonthWithTimeZone:self.timeZone];
	
	NSDateComponents *nextInfo = [nextMonth dateComponentsWithTimeZone:self.timeZone];
	NSDate *localNextMonth = [NSDate dateWithDateComponents:nextInfo];
	
	NSArray *dates = [CalendarMonthTiles  rangeOfDatesInMonthGrid:nextMonth startOnSunday:self.sunday timeZone:self.timeZone];
	NSArray *ar = [self.dataSource calendarMonthView:self marksFromDate:dates[0] toDate:[dates lastObject]];
	CalendarMonthTiles *newTile = [[CalendarMonthTiles alloc] initWithMonth:nextMonth marks:ar startDayOnSunday:self.sunday timeZone:self.timeZone];
	[newTile setTarget:self action:@selector(_tileSelectedWithData:)];
	
	NSInteger overlap =  0;
	
//	if(isNext)
//		overlap = [newTile.monthDate isEqualToDate:dates[0]] ? 0 : 47;
//	else
//		overlap = [self.currentTile.monthDate compare:[dates lastObject]] !=  NSOrderedDescending ? 47 : 0;
	
	
	float y = isNext ? CGRectGetHeight(self.currentTile.frame) + 67 : CGRectGetHeight(newTile.frame) * -1 + overlap;
	
	newTile.frame = CGRectMakeWithSize(0, y, newTile.frame.size);
	newTile.alpha = 0;
//	[self addSubview:newTile];
    [self insertSubview:newTile belowSubview:self.shadowView];
	
	
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.1];
	newTile.alpha = 1;
    
	[UIView commitAnimations];
	
	self.userInteractionEnabled = NO;
	
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationDidStopSelector:@selector(animationEnded)];
	[UIView setAnimationDelay:0.1];
	[UIView setAnimationDuration:0.4];
	
	
	
	if(isNext){
		self.currentTile.frame = CGRectMakeWithSize(0, -1* CGRectGetHeight(self.currentTile.frame)+overlap,  self.currentTile.frame.size);
		newTile.frame = CGRectMakeWithSize(0, 67, newTile.frame.size);
	}else{
		newTile.frame = CGRectMakeWithSize(0, 67 , newTile.frame.size);
		self.currentTile.frame = CGRectMakeWithSize(0, CGRectGetHeight(newTile.frame) + overlap, self.currentTile.frame.size);
	}
	
//	[self _updateSubviewFramesWithTile:newTile];
    
	[UIView commitAnimations];
	
	self.oldTile = self.currentTile;
	self.currentTile = newTile;
//	_monthYear.text = [localNextMonth monthYearStringWithTimeZone:self.timeZone];
	
    
}
- (void) animationEnded{
	self.userInteractionEnabled = YES;
	[self.oldTile removeFromSuperview];
	self.oldTile = nil;
}

#pragma mark Private Methods for setting up tiles

//- (void) _updateSubviewFramesWithTile:(UIView*)tile{
//	self.tileBox.frame = CGRectMake(0, TOP_BAR_HEIGHT-1,VIEW_WIDTH, CGRectGetHeight(tile.frame));
//	self.frame = CGRectMakeWithPoint(self.frame.origin, VIEW_WIDTH, CGRectGetMaxY(self.tileBox.frame));
//	self.shadow.frame = self.tileBox.frame;
//	self.dropshadow.frame = [self _calculatedDropShadowFrame];
//}
- (void) _setupCurrentTileView:(NSDate*)date{
	if(self.currentTile) return;
	
	NSDate *month = [date firstOfMonthWithTimeZone:self.timeZone];
	NSArray *dates = [CalendarMonthTiles rangeOfDatesInMonthGrid:month startOnSunday:self.sunday timeZone:self.timeZone];
	NSArray *data = [self.dataSource calendarMonthView:self marksFromDate:dates[0] toDate:[dates lastObject]];
	
	self.currentTile = [[CalendarMonthTiles alloc] initWithMonth:month marks:data startDayOnSunday:self.sunday timeZone:self.timeZone];
    self.currentTile.frame = CGRectMake(0, 67, VIEW_WIDTH, CGRectGetHeight(self.currentTile.frame));

    [self insertSubview:self.currentTile belowSubview:self.shadowView];
	[self.currentTile setTarget:self action:@selector(_tileSelectedWithData:)];
//	
//	[self.tileBox addSubview:self.currentTile];
//	
//	self.monthYear.text = [date monthYearStringWithTimeZone:self.timeZone];
//	[self _updateSubviewFramesWithTile:self.currentTile];
	
}

#pragma mark - Propertys

-(UIButton *)rightArrow{
    if (_rightArrow) {
        return _rightArrow;
    }
    _rightArrow = [UIButton buttonWithType:UIButtonTypeCustom];
	_rightArrow.tag = 1;
	_rightArrow.frame = CGRectMake(VIEW_WIDTH-35, 20, 35, 30);
	_rightArrow.accessibilityLabel = @"Next Month";
	[_rightArrow addTarget:self action:@selector(changeMonth:) forControlEvents:UIControlEventTouchUpInside];
	[_rightArrow setImage:[UIImage imageNamed:@"cal_arrow_next"] forState:0];
    return _rightArrow;
}
-(UIButton *)leftArrow{
    if (_leftArrow) {
        return _leftArrow;
    }
    _leftArrow = [UIButton buttonWithType:UIButtonTypeCustom];
    _leftArrow.tag = 0;
    _leftArrow.frame = CGRectMake(0, 20, 35 , 30);
    _leftArrow.accessibilityLabel = @"Previous Month";
	[_leftArrow addTarget:self action:@selector(changeMonth:) forControlEvents:UIControlEventTouchUpInside];
	[_leftArrow setImage:[UIImage imageNamed:@"cal_arrow_back"] forState:0];

    return _leftArrow;
}
-(UIView *)shadowView{
    if (_shadowView) {
        return _shadowView;
    }
    _shadowView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 67)];
    [_shadowView setBackgroundColor:[UIColor whiteColor]];
    return _shadowView;
}
-(UILabel *)monthLabel{
    if (_monthLabel) {
        return _monthLabel;
    }
    _monthLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, 20, 50, 30)];
    [_monthLabel setTextAlignment:NSTextAlignmentCenter];
    [_monthLabel setText:@"八月"];
    [_monthLabel setFont:[UIFont systemFontOfSize:16]];
    return _monthLabel;
}

-(UILabel *)yearLabel{
    if (_yearLabel) {
        return _yearLabel;
    }
    _yearLabel = [[UILabel alloc] initWithFrame:CGRectMake(VIEW_WIDTH-35-50, 20, 50, 30)];
    [_yearLabel setTextAlignment:NSTextAlignmentCenter];
    [_yearLabel setFont:[UIFont systemFontOfSize:15]];
    [_yearLabel setText:@"2014"];
    [_yearLabel setTextColor:[UIColor lightGrayColor]];
    return _yearLabel;
    
}

- (NSDate*) dateSelected{
	if(self.currentTile==nil) return nil;
	return [self.currentTile dateSelected];
}
@end
